//
//  CTSlideInPresentationAnimator.swift
//  Swift-Tools
//
//  Created by gree on 2020/10/16.
//

import UIKit

class CTSlideInPresentationAnimator: NSObject {
    
    /// 方向
    let direction: CTPresentationDirection
    /// 判断是进入还是要消失 true:进入，false：消失
    let isPresentation: Bool
    
    init(direction: CTPresentationDirection, isPresentation: Bool) {
        self.direction = direction
        self.isPresentation = isPresentation
        super.init()
    }
}

extension CTSlideInPresentationAnimator: UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.3
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let key = isPresentation ? UITransitionContextViewControllerKey.to : UITransitionContextViewControllerKey.from
        guard let controller = transitionContext.viewController(forKey: key) else {
            return
        }
        
        if isPresentation {
            transitionContext.containerView.addSubview(controller.view)
        }
        
        var presentedFrame = transitionContext.finalFrame(for: controller)
        var dismissedFrame = presentedFrame
        
        switch direction {
            case .bottom(_, let height):
                dismissedFrame.size.height = height
                presentedFrame.size.height = height
                dismissedFrame.origin.y = transitionContext.containerView.frame.size.height
                presentedFrame.origin.y = UIScreen.main.bounds.height - height
            case .left(let width, _):
                dismissedFrame.size.width = width
                presentedFrame.size.width = width
                presentedFrame.origin.x = 0
                dismissedFrame.origin.x = -width
            case .right(let width, _):
                dismissedFrame.size.width = width
                presentedFrame.size.width = width
                dismissedFrame.origin.x = UIScreen.main.bounds.width
            case .top(_, let height):
                dismissedFrame.size.height = height
                presentedFrame.size.height = height
                dismissedFrame.origin.y -= presentedFrame.height
        }
        
        let initializeFrame = isPresentation ? dismissedFrame : presentedFrame
        let finalFrame = isPresentation ? presentedFrame: dismissedFrame
        
        let animationDuration = transitionDuration(using: transitionContext)
        controller.view.frame = initializeFrame
        print("finalFrame: \(finalFrame)")
        print("initializeFrame: \(finalFrame)")

        UIView.animate(withDuration: animationDuration) {
            controller.view.frame = finalFrame
        } completion: { (finished) in
            transitionContext.completeTransition(finished)
        }
    }
}
